﻿using M.WWHours.API.Command.WWHoursCommand;
using M.WWHours.Domain.Dto;
using M.WWHours.Domain.Model;
using M.WWHours.Repository.WWHoursImpl;
using M.WWHours.Repository.WWHoursInterface;
using MediatR;

namespace M.WWHours.API.CommandHandlers.WWHoursCommandHandler
{
    /// <summary>
    /// 显示工时命令处理器
    /// </summary>
    public class ShowWWHoursCommandHandler : IRequestHandler<ShowWWHoursCommand, WWorkingHoursDto<WWorkingHours>>
    {
        /// <summary>
        /// 工时工时仓储接口
        /// </summary>
        protected readonly IWWHoursRepository wWHoursRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="wWHoursRepository">工时工时仓储接口</param>
        public ShowWWHoursCommandHandler(IWWHoursRepository wWHoursRepository)
        {
            this.wWHoursRepository = wWHoursRepository;
        }

        /// <summary>
        /// 处理显示工时命令
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<WWorkingHoursDto<WWorkingHours>> Handle(ShowWWHoursCommand request, CancellationToken cancellationToken)
        {
            var list = from a in await wWHoursRepository.GetAllAsync()
                       where !a.IsDeleted
                       select new WWorkingHours()
                       {
                           WWHoursId = a.WWHoursId,
                           WorkerNumber = a.WorkerNumber,
                           WorkersName = a.WorkersName,
                           Department = a.Department,
                           PhoneNumber = a.PhoneNumber,
                           WorkingHours = a.WorkingHours,
                           RestDuration = a.RestDuration,
                           Status = a.Status,
                       };

            if (!string.IsNullOrEmpty(request.WorkerNumber))
            {
                list = list.Where(x => x.WorkerNumber.Contains(request.WorkerNumber));
            }

            if (!string.IsNullOrEmpty(request.Status))
            {
                list = list.Where(x => x.Status.Contains(request.Status));
            }

            if (request.PageIndex == null)
            {
                request.PageIndex = 1;
            }

            if (request.PageSize == null)
            {
                request.PageSize = 15;
            }

            WWorkingHoursDto<WWorkingHours> page = new WWorkingHoursDto<WWorkingHours>();
            page.TotalCount = list.Count();
            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / (int)request.PageSize);
            page.list = list.OrderByDescending(x => x.CreatedDate).Skip((int)request.PageIndex - 1).Take((int)request.PageSize).ToList();
            return page;
        }
    }
}
